import axios from 'axios'
import requestConfig from '@/config/request'
import { useUserStore } from '@/store/user'
import router from '../router'
import { downFileByBlob } from '@/utils/index'

import { baseUrl } from '@/env.config'
import { isRef } from 'vue'
const service = axios.create({
  // 判断是本地运行走代理还是线上运行直接连
  baseURL: baseUrl,
  timeout: 60000, // 请求超时时间
})

// 白名单接口，不需要添加token   请求前
service.interceptors.request.use(async (config) => {
  const { token } = storeToRefs(useUserStore())
  const { url, loading, noToken } = config
  if (!noToken) {
    if (!token.value) {
      const { logout } = useUserStore()
      ElMessage.error('登录失效，请重新登录！')
      await logout()
      router.push('/login')
      return false
    }
    config.headers['h-authorization-token'] = token.value
  }
  if (loading) {
    loading.value = true
  }
  return config
})

//请求后处理
service.interceptors.response.use(async (res) => {
  console.log(res, 'res');

  const { status, statusText, data: resData, config } = res
  const { autoUntie, loading, resField } = config
  isRef(loading) && (loading.value = false)
  if (status !== 200) {
    ElMessage.error(statusText)
    return
  } else {
    const { code, msg, unLogin } = resData
    // 登录失效则直接回到登录页
    if (unLogin) {
      const { logout } = useUserStore()
      ElMessage.error(msg)
      router.push('/login')
      await logout()
      return
    }
    // resField:获取接口响应数据里面的哪个字段当作返回值
    const data = resData[resField || requestConfig.resField]
    // autoUntie为单独为该请求设置的是否拆包
    // requestConfig.autoUntie为全局配置的是否拆包
    // 优先级 autoUntie > requestConfig.autoUntie
    if (autoUntie || (autoUntie !== false && requestConfig.autoUntie)) {
      if (code === 200) {
        return Promise.resolve(data)
      } else {
        ElMessage.error(msg)
        return Promise.reject(resData)
      }
    } else {
      return Promise.resolve(resData)
    }
  }
}, err => {
  const { message, config } = err
  const { loading, autoUntie } = config
  isRef(loading) && (loading.value = false)
  // 如果是拆包则提示，如果不是则直接返回让他自己处理错误信息
  if (autoUntie) {
    ElMessage.error(message)
  } else {
    return Promise.reject(err)
  }
})

export default service
